import React, {PureComponent} from "react";
import {Form, Tree, Input} from 'antd';
import PropTypes from "prop-types";
import menuList from '../../config/menuConfig'

const Item = Form.Item;
const { TreeNode } = Tree;

export default class AuthForm extends PureComponent{
    static propTypes = {
        role: PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);
        const {menus} = props.role;
        // 初始状态
        this.state = {
            checkedKeys: menus
        }
    }

    getTreeNodes = (menuList) => {
        return menuList.reduce((pre,item) => {
            pre.push(
                <TreeNode title={item.title} key={item.key} >
                    {item.children ? this.getTreeNodes(item.children) : null}
                </TreeNode>
            );
            return pre;
        }, [])
    };

    onCheck = checkedKeys => {
        console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });
    };

    getMenus = () => {
        const menus = this.state.checkedKeys;
        return menus;
    };

    // 根据新传入的role来更新checkedKeys状态
    componentWillReceiveProps(nextProps, nextContext) {
        const menus = nextProps.role.menus
        this.setState({
            checkedKeys: menus
        })
    }

    componentWillMount() {
        this.treeNodes = this.getTreeNodes(menuList);
    }

    render() {
        const {role} = this.props;
        const {checkedKeys} = this.state;

        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 18 },
        };

        return (
            <div>
                <Item label='角色名称：' {...formItemLayout}>
                    {
                        <Input value={role.name} disabled/>
                    }
                </Item>

                <Tree
                    checkable
                    defaultExpandAll
                    checkedKeys={checkedKeys}
                    onCheck={this.onCheck}
                >
                    <TreeNode title="平台权限" key="all">
                        {this.treeNodes}
                    </TreeNode>
                </Tree>
            </div>
        );
    }
}